<?php
namespace App\Http\Controllers\Company;

use App\Models\CompanyType;
use App\Models\CompanyScale;
use App\Models\CompanyDevelop;
use Illuminate\Http\Request;
use App\Models\Company;
use App\Models\CompanyAddress;
use Illuminate\Support\Facades\DB;
use App\Models\CompanyTypeLink;
use Illuminate\Support\Facades\Log;
use App\Models\Area;
use App\Models\Tags;
use App\Models\CompanyTags;
use App\Models\CompanyPhoto;
/**
 *
 * @author Joker
 *        
 */
class InfoController extends CompanyController
{
    private $types;
    
    public function __construct()
    {
        parent::__construct();
        $this->types = CompanyType::where('parent_id','=',0)->orderBy('sort','ASC')->get();
    }
    
    /**
     * 企业资料
     * @return [type] [description]
     */
    public function companyinfo($type)
    {
        
        $scales = CompanyScale::all();
        $develops = CompanyDevelop::all();
        $upload_field = array('dest_dir'=>'companylogo','_token'=>csrf_token(),'attachment'=>false);
        $options =  str_replace('"','\'',json_encode($upload_field));
        $opts = base64_encode(serialize($upload_field));
        
        if($this->userinfo->company_id > 0 && !empty($this->userinfo->company_id))
        {
            $company = Company::find($this->userinfo->company_id);
            $address = $company->addressinfo;
            $company->comtype = array_fetch($company->types->toArray(),'type_id');
            $subarea= Area::where('pid','=',$address->province)->orderBy('sort','ASC')->get();
            $thrarea= Area::where('pid','=',$address->city)->orderBy('sort','ASC')->get();
            $taglink = $company->tags;
            $tags = array();
            if(count($taglink)>0)
            {
                foreach ($taglink as $res)
                {
                    $tags[] = Tags::where('tags_id','=',$res->tags_id)->first()->tags_name;
                }
            }
            $photos = CompanyPhoto::where('company_id','=',$this->userinfo->company_id)->orderBy('created_at','DESC')->get();
            return view('company.infomation')
                ->with('result',$company)
                ->with('address',$address)
                ->with('area', $this->area)
                ->with('subarea',$subarea)
                ->with('thrarea',$thrarea)
                ->with('tags',$tags)
                ->with('photos',$photos)
                ->with('blademode','edit')
                ->with('scales',$scales)
                ->with('develops',$develops)
                ->with('types',$this->types)
                ->with('options',$options)
                ->with('opts',$opts)
                ->with('type', $type);
        }
        else 
        {
            return view('company.infomation')
                    ->with('nav', $this->nav)
                    ->with('area', $this->area)
                    ->with('blademode','add')
                    ->with('scales',$scales)
                    ->with('develops',$develops)
                    ->with('types',$this->types)
                    ->with('options',$options)
                    ->with('opts',$opts)
                    ->with('type', $type);
        }
    }
    
    /**
     * 企业信息保存
     * @param Request $req
     */
    public function store(Request $req)
    {
        $this->validate($req, [
            'name'          => 'required|max:255',
            'email'         => 'required|email|max:255',
            'phone'         => 'required|numeric',
            'signature'     => 'required|max:255',
            'province'      => 'required',
            'city'          => 'required',
            'area'          => 'required',
            'intro'         => 'required|min:40',
            'ctype'         => 'required' 
        ]);
        $data = $req->only('name','signature','logo','intro','email','phone','main_page','scale','authtype','tel','zip_code',
            'bus_route','created_uid','blademode','add_id','province','city','area','address','longitude','latitude','ctype');
        $hasuser = Company::where('name','=',$data['name'])->where('id','<>',$this->userinfo->company_id)->first();
        if(!empty($hasuser))
        {
            return $this->formatJson('error','该公司已在网站注册');
        }
        if($data['blademode'] == 'edit' && $this->userinfo->company_id > 0 && is_numeric($data['add_id']) && $data['add_id'] > 0)
        {
            $company = Company::find($this->userinfo->company_id);
            if(empty($company))
                return $this->formatJson('error','您的公司不存在，或已被管理员删除，请联系管理员！');
            $address = CompanyAddress::find($data['add_id']);
            $company->name      = $data['name'];
            $company->signature = $data['signature'];
            $company->logo      = $data['logo'];
            $company->intro     = $data['intro'];
            $company->email     = $data['email'];
            $company->phone     = $data['phone'];
            $company->main_page = $data['main_page'];
            $company->scale_id  = $data['scale'];
            $company->develop_id = 0;
            $company->auth_id   = $data['authtype']?:0;
            $company->tel        = $data['tel'];
            $company->zip_code  = $data['zip_code'];
            $company->bus_route = $data['bus_route'];
            $company->updated_user_id = $this->userinfo->id;
            if($company->created_uid == 0)
                $company->created_uid = $this->userinfo->id;
            DB::beginTransaction();
            try {
                $company->save();
                //begin by hex 2015-11-15 新增地址信息保存
                $address->company_id = $company->id;
                $address->province = $data['province'];
                $address->city = $data['city'];
                $address->area = $data['area'];
                $address->address = $data['address'];
                $address->longitude = $data['longitude'];
                $address->latitude = $data['latitude'];
                $address->save();
                $ctype = $data['ctype'];
                CompanyTypeLink::where('company_id','=',$company)->delete();
                foreach ($ctype as $ctp)
                {
                    CompanyTypeLink::firstOrCreate(['company_id'=>$company->id,'type_id'=>$ctp]);
                }
                $this->userinfo->company_id = $company->id;
                $this->userinfo->save();
                DB::commit();
            }catch (\PDOException $e){
                DB::rollback();
                Log::info(['企业信息保存失败'=>$e->getMessage()]);
                return $this->formatJson('falied','企业数据保存失败！');
            }
        }
        else
        {
            $address = new CompanyAddress();
//             $company->created_uid = $this->uid;
            $insertArray = array(
                'name'          => $data['name'],
                'created_uid'   => $this->userinfo->id,
                'signature'     => $data['signature'],
                'logo'          => $data['logo'],
                'intro'         => $data['intro'],
                'email'         => $data['email'],
                'phone'         => $data['phone'],
                'main_page'     => $data['main_page'],
                'scale_id'      => $data['scale'],
                'develop_id'    => 0,
                'auth_id'       => $data['authtype']?:0,
                'tel'           => $data['tel'],
                'zip_code'      => $data['zip_code'],
                'bus_route'     => $data['bus_route'],
                'updated_user_id'=> $this->userinfo->id
            );
            DB::beginTransaction();
            try {
                $company = Company::firstOrCreate($insertArray);
                //begin by hex 2015-11-15 新增地址信息保存
                $address->company_id = $company->id;
                $address->province = $data['province'];
                $address->city = $data['city'];
                $address->area = $data['area'];
                $address->address = $data['address'];
                $address->longitude = $data['longitude'];
                $address->latitude = $data['latitude'];
                $address->save();
                $ctype = $data['ctype'];
                CompanyTypeLink::where('company_id','=',$company)->delete();
                foreach ($ctype as $ctp)
                {
                    CompanyTypeLink::firstOrCreate(['company_id'=>$company->id,'type_id'=>$ctp]);
                }
                $this->userinfo->company_id = $company->id;
                $this->userinfo->save();
                DB::commit();
            }catch (\PDOException $e){
                DB::rollback();
                Log::info(['企业信息创建失败'=>$e->getMessage()]);
                return $this->formatJson('falied','企业数据保存失败！');
            }
            
        }
       
        return $this->formatJson('success','企业信息保存成功！',$company);
    }
    
    /**
     * 更多信息保存
     * @param Request $req
     */
    public function moreinfoSave(Request $req)
    {
        if($this->userinfo->company_id > 0 && !empty($this->userinfo->company_id))
        {
            $company = Company::find($this->userinfo->company_id);
            if(empty($company)) 
                return $this->formatJson('error','您的公司不存在，或已被管理员删除，请联系管理员！');
            
            $data = $req->only('develop','investment','tags');
            DB::beginTransaction();
            try{
                if(!empty($data['develop']))
                {
                    $company->develop_id = $data['develop'];
                    if($data['investment'])
                        $company->investment = $data['investment'];
                }
                if(!empty($data['tags']))
                {
                    $tagids = array();
                    foreach ($data['tags'] as $tg)
                    {
                        if(!empty(trim($tg)))
                        {
                            $tagsModel = Tags::firstOrCreate(['tags_name'=>trim($tg)]);
                            $tagids[] = $tagsModel->tags_id;
                        }
                    }   
                    //建立关联 文章与标签
                    CompanyTags::where('company_id','=',$company->id)->delete();
                    foreach ($tagids as $tgd){
                        CompanyTags::firstOrCreate(['tags_id'=>$tgd,'company_id'=>$company->id]);
                    }
                }
                $company->save();
                DB::commit();
            }catch (\PDOException $e){
                DB::rollback();
                Log::info(['企业附加信息创建失败'=>$e->getMessage()]);
                return $this->formatJson('falied','数据保存失败！');
            }
            return $this->formatJson('success','保存成功！');
        }
        else
        {
            return redirect('/company/center/companyinfo-default');
        }
    }
    
    /**
     * 验证
     * @param Request $req
     */
    public function check(Request $req)
    {
        $name = $req->input('name','');
        if(!empty($name))
        {
            $hasuser = Company::where('name','=',$name)->where('id','<>',$this->userinfo->company_id)->first();
            if($hasuser)
            {
                return $this->formatJson('error','该公司已在网站注册');
            }
            else
            {
                return $this->formatJson('success','该公司可用');
            }
        }
        $email = $req->input('email','');
        if(!empty($email))
        {
            $haseamil = Company::where('email','=',$email)->where('id','<>',$this->userinfo->company_id)->first();
            if($haseamil)
            {
                return $this->formatJson('error','邮箱已存在');
            }
            else
            {
                return $this->formatJson('success','邮箱可用');
            }
        }
        $phone = $req->input('phone','');
        if(!empty($phone))
        {
            $hasphone = Company::where('phone','=',$phone)->where('id','<>',$this->userinfo->company_id)->first();
            if($hasphone)
            {
                return $this->formatJson('error','手机号已存在');
            }
            else
            {
                return $this->formatJson('success','手机号可用');
            }
        }
    }

    public function destroy(Request $req)
    {
        $imageid = $req->input('imageid','');
        $imageinfo = CompanyPhoto::find($imageid);

        if(empty($imageinfo))
        {
            return  $this->formatJson('falied','抱歉，资源不存在!');
        }
        else
        {
           $imageinfo->delete();
           unlink(public_path($imageinfo->path));
           return $this->formatJson('success','图片删除成功！');
        }
    }
}